using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using csvviewer.contracts;

namespace csvviewer.portal
{
    public class UI
    {
		private IEnumerable<string> _linesToDisplay;
		private AutoResetEvent _areDisplay = new AutoResetEvent(false);
		private bool _looping = true;
		
		
        public void ScheduleDisplay(IEnumerable<string> lines)
        {
			_linesToDisplay = lines;
			_areDisplay.Set();
        }
		
		

		public void Run()
		{
			while(_looping)
			{
				_areDisplay.WaitOne();
				
				Display(_linesToDisplay);
				Wait_for_user_interaction ();
			}
		}
		
		
		public event Action<PageDirections> TurnToPage;
		public event Action<int> JumpToPage;
			
			
		void Display(IEnumerable<string> lines)
		{
			Console.WriteLine("\nCSV Viewer v0.9");
        	foreach (var line in lines)
        	    Console.WriteLine("{0}", line);
 		}
		
		
		void Wait_for_user_interaction()
		{
			Console.Write("\nF(irst, N(ext, P(rev, L(ast, J(ump, eX(it: ");
			var cmd = Console.ReadKey().KeyChar.ToString().ToLower();
			Console.WriteLine();
			
			switch(cmd)
			{
			case "x": _looping = false; return;
			case "f": this.TurnToPage(PageDirections.First); break;		
			case "l": this.TurnToPage(PageDirections.Last); break;
			case "p": this.TurnToPage(PageDirections.Previous); break;
			case "n": this.TurnToPage(PageDirections.Next); break;
			case "j": 
				Console.Write("  Page number: ");
				var pageNo = int.Parse(Console.ReadLine());
				this.JumpToPage(pageNo);
				break;
			}
		}
    }
}
